package cn.virens.web.components.beetl.fun;

import java.util.Collection;
import java.util.Map;

import org.beetl.core.Context;
import org.beetl.core.Function;

import cn.hutool.core.util.ArrayUtil;
import cn.virens.database.common.BaseEnum;

public class FormCheckFunction implements Function {
	private static final String YES = "checked";
	private static final String NO = "";

	@Override
	public String call(Object[] paras, Context ctx) {
		if (paras == null || paras.length < 2) { return NO; }

		Object obj = paras[0];
		Object[] values = null;

		// 将可选项转换为数组	
		if (ArrayUtil.isArray(obj)) {
			values = (Object[]) obj;
		} else if (obj instanceof String) {
			values = ((String) obj).split(",");
		} else if (obj instanceof Collection) {
			values = ((Collection<?>) obj).toArray();
		} else if (obj instanceof Map) {
			values = ((Map<?, ?>) obj).values().toArray();
		}

		if (values == null || values.length == 0) { return NO; }

		// 检查数据中是否存在当前选项值
		Object v = paras[1];
		for (Object o : values) {
			if (eq1(o, v) || eq2(o, v)) { return YES; }
		}

		return NO;
	}

	private static boolean eq1(Object o, Object v) {
		return o != null && o.equals(v);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private static boolean eq2(Object o, Object v) {
		return o instanceof BaseEnum && ((BaseEnum) o).eq(v);
	}

}
